package com.ysd.lis.util.qcrule;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class AOfNLRule extends Rule{
    public AOfNLRule(String id, String name, int a, int n, double l) {
        super(id, name, a, n, l);
        this.type = RuleType.AXRule;
    }

    @Override
    public RuleStatement Evaluate(QCResult result) {
        if (result.getResults().size() < n)
        {
            return RuleStatement.DISABLE;
        }



        List<Result> results = result.getResults();
        //var items = result.Results.GetRange(result.Results.Count - N, N);
        List<Result> items = new ArrayList<>();
        for(int i = 0 ;i< n; i++){
            items.add(results.get(results.size()-n+i));
        }

        if (HasEmptyResult(items))
        {
            return RuleStatement.DISABLE;
        }


        //var hs = items.Where(p => p.Z >  L).ToList();
        List<Result> hs = items.stream().filter(p -> p.getZvalue() > l).collect(Collectors.toList());
        //var ls = items.Where(p => p.Z <  L * -1).ToList();
        List<Result> ls = items.stream().filter(p -> p.getZvalue() <l*-1).collect(Collectors.toList());


        if (hs.size() >= a || ls.size() >= a)
        {
            items.get(items.size()-1).setIsOutControl(true);

            items.get(items.size()-1).getOutControlInfos().add(new OutControlInfo(id,false,
                    hs.size()>=a?hs.stream().map(Result::getId).collect(Collectors.toList()) :
                    ls.stream().map((Result::getId)).collect(Collectors.toList())));
//            {
//                RuleId = Id,
//                IsMutiMaterial = false,
//                MemberIds = hs.Count() >= A ? hs.Select(p => p.Id).ToList() : ls.Select(p => p.Id).ToList()
//            });


            return RuleStatement.OK;
        }


        return RuleStatement.FAILED;
    }

    @Override
    protected QCResult ListToQCResult(List<QCResult> results) {
        //if (!results.Any())
        if(CollectionUtils.isEmpty(results))
        {
            return null;
        }

        //仅判断质控品最后一次,且N=质控物数
        if (n != results.size())
        {
            return null;
        }


        //每个质控品必须有一个数据
        //if (results.Select(p => p.Results.Count).Min() < 1)
        List<QCResult> collect = results.stream().filter(a -> a.getResults().size() < 1).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(collect))
        {
            return null;
        }

        QCResult result = new QCResult();

        //获取必要数据
        for (QCResult r : results)
        {

            result.getResults().add(r.getResults().get(r.getResults().size()-1));
        }

        return result;
    }
}
